package org.nvm.core;

import java.util.Stack;
import java.util.TreeSet;

public class NVMArbitrator {
	
	public NVMArbitrator() {
		
	}
	
	public void process(AnalyzeContext context, boolean isSmart) {
		//获取原始分词链
		QuickSortSet orgLexemePath = context.getOrgLexemes();
		
		Lexeme orgLexeme = orgLexemePath.shiftHead();
		
		LexemePath crossPath = new LexemePath();
		while(orgLexeme != null) {
			//添加相交的次元
			if(!crossPath.addCrossLexeme(orgLexeme)) {
				if(crossPath.size() == 1 || !isSmart) {
					context.addLexemePath(crossPath);
				} else {
					LexemePath judgeResult = this.judge(context, crossPath.getHeadCell(), crossPath.getPathLength());
					context.addLexemePath(judgeResult);
				}
				
				crossPath = new LexemePath();
				crossPath.addCrossLexeme(orgLexeme);
			}
			
			orgLexeme = orgLexemePath.shiftHead();
		}
		
		if(crossPath.size() == 1 || !isSmart) {
			context.addLexemePath(crossPath);
		} else if(crossPath.getHeadCell() != null) {
			LexemePath judgeResult = this.judge(context, crossPath.getHeadCell(), crossPath.getPathLength());
			context.addLexemePath(judgeResult);
		}
	}
	
	
	private LexemePath judge(AnalyzeContext context, QuickSortSet.Cell ambiguityCell, int textLength) {
		
		TreeSet<LexemePath> resultOptions = new TreeSet<>();
		
		LexemePath basePath = new LexemePath(context.getSegmentBuff(), ambiguityCell.getLexeme().getBegin(), textLength);
		
		Stack<QuickSortSet.Cell> stacks = this.forwardPath(ambiguityCell, basePath);
		
		resultOptions.add(basePath.copy());
		
		QuickSortSet.Cell index = null;
		while(!stacks.isEmpty()) {
			index = stacks.pop();
			
			this.backPath(index.getLexeme(), basePath);
			
			this.forwardPath(index, basePath);
			
			resultOptions.add(basePath.copy());
			
		}
		
		return resultOptions.last();
	}
	
	private Stack<QuickSortSet.Cell> forwardPath(QuickSortSet.Cell ambiguityCell, LexemePath option) {
		Stack<QuickSortSet.Cell> stack = new Stack<>();
		
		QuickSortSet.Cell cursorCell = ambiguityCell;
		
		while(cursorCell != null && cursorCell.getLexeme() != null) {
			if(!option.addNotCrossLexeme(cursorCell.getLexeme())) {
				stack.push(cursorCell);
			}
			cursorCell = cursorCell.getNext();
		}
		
		return stack;
	}
	
	private void backPath(Lexeme l, LexemePath option) {
		if(option.checkCross(l)) {
			option.removeTail();
		}
	}
}
